﻿using Playnite.SDK.Models;
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImportExporter.ImportAttributes
{
    public static class ImportPlatforms
    {
        public static void DoImportPlatforms(IPlayniteAPI PlayniteApi, Game game, List<Platform> importedPlatformList)
        {
            List<Platform> existedPlatformList = PlayniteApi.Database.Platforms.ToList();

            // 在imported中根据Id找Name（这个是一定能找到的）
            List<Platform> spcificationExistsPlatformList = importedPlatformList.Where<Platform>(item =>
            {
                if (game.PlatformIds != null)
                {
                    return game.PlatformIds.Contains(item.Id);
                }
                else
                {
                    return false;
                }
            }).ToList();
            // 在existed中根据Name找Id（这个不一定能找到，imported来的可能是新的）
            if (game.PlatformIds != null)
            {
                game.PlatformIds.Clear();
                foreach (Platform platform in spcificationExistsPlatformList)
                {
                    List<Platform> foundList = existedPlatformList.FindAll(p => p.SpecificationId.Trim().Equals(platform.SpecificationId.Trim(), StringComparison.OrdinalIgnoreCase)).ToList();
                    if (foundList.Count > 0)
                    {
                        game.PlatformIds.Add(foundList[0].Id);
                    }
                    else
                    {
                        PlayniteApi.Database.Platforms.Add(platform);
                        game.PlatformIds.Add(platform.Id);
                    }
                }
            }
        }
    }
}
